package com.bardsoftware.foronuvolo.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;


import org.compass.annotations.Searchable;
import org.compass.annotations.SearchableId;

@PersistenceCapable(identityType=IdentityType.APPLICATION)
@Searchable
public class FeedForListening {
	
	@PrimaryKey	
	@SearchableId
	private String feedUrl;
	
	@Persistent
	private String urlCopy;
	
	@Persistent
	private ArrayList<String> userIds;
	
	@Persistent
	private Date lastUpdate;
	
	private static final Logger LOGGER = Logger.getLogger(Discussion.class.getName());
	
	public FeedForListening(String url, ArrayList<String> users) {
		feedUrl = url;
		urlCopy = url;
		userIds = users;
		lastUpdate = new Date();
	}
	public String getUrl() {
		return urlCopy;
	}
	public Date getLastUpd() {
		return lastUpdate;
	}
	public void setLastUpdate(Date newDate) {
		lastUpdate = newDate;
	}
	public String getFeedURL() {
		return feedUrl;
	}
	public ArrayList<String> getSubscribers() {
		return userIds;
	}
	public void addSubscriber(final String userId) {
		boolean res = PMF.runInTransaction(this, new Runnable() {			
			@Override
			public void run() {
				FeedForListening.this.getSubscribers().add(userId);
			}
		},3);
		if(!res) {
			LOGGER.severe("Failed to add user=" + userId);
		}
	}
	public static FeedForListening find(String url) {	
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();
		try {
			FeedForListening res = pm.getObjectById(FeedForListening.class,url);
			res = pm.detachCopy(res);
			return res;
		}
		catch(JDOObjectNotFoundException e) {
			return null;
		}
		finally {
			pm.close();
		}
	}	
	public void save() {
		boolean res = PMF.runInTransaction(this,new Runnable() {
			
			@Override
			public void run() {				
			}
		},3);
		if(!res) {
			LOGGER.severe("Failed to save feed=" + getFeedURL());
		}
	}
	public static Collection<FeedForListening> getAllFeeds() {
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();
		try {
			String query = "select from " + FeedForListening.class.getName();
			List<FeedForListening> result = (List<FeedForListening>)pm.newQuery(query).execute();
			return result.isEmpty()? null : pm.detachCopyAll(result);
		}
		finally {
			pm.close();
		}
	}
}
